//
//  CommonMethod.m
//  OneCard
//
//  Created by sally on 16/2/16.
//  Copyright © 2016年 koalac. All rights reserved.
//

#import "CommonMethod.h"
#import "UIView+Toast.h"

@implementation CommonMethod
singleton_implementation(CommonMethod)

- (MBProgressHUD *)createProgressHUDInView:(UIView *)view withMessage:(NSString *)message {
  MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
  hud.mode = MBProgressHUDModeIndeterminate;
  
  if (message) {
    hud.labelText = message;
  } else {
    hud.labelText = @"正在加载";
  }
  
  return hud;
}

//在View中显示Toast
- (void)showToastInCenter:(UIView *)view withMessage:(NSString *)message {
  // 针对网络连接失败时的提示信息处理
  NSArray *errorDomains = @[ @"NSURLErrorDomain" ];//, @"NSCocoaErrorDomain"
  if ([errorDomains containsObject:message]) {
    message = NETWORK_DESCRIPTION;
  }else if ([message rangeOfString:@"Error"].length>0){
    message = FAILURE_DESCRIPTION;
  }
  
  [view makeToast:message duration:1.0 position:CSToastPositionCenter];
}

//显示提示框
- (void)showAlertMessage:(NSString *)message {
  // 针对网络连接失败时的提示信息处理
  NSArray *errorDomains = @[ @"NSURLErrorDomain"];//, @"NSCocoaErrorDomain"
  if ([errorDomains containsObject:message]) {
    message = NETWORK_DESCRIPTION;
  }else if ([message rangeOfString:@"Error"].length>0){
    message = FAILURE_DESCRIPTION;
  }
  
  [UIAlertView showWithTitle:@"提示" message:message cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
  }];
}

//设置导航栏btnItem
- (void)setNavButtonItem:(UIBarButtonItem *)buttonItem type:(ButtonItemType)type{
  NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
  if (type == ButtonItemType_Gray) {
    attrs[NSForegroundColorAttributeName] = GGrayWordColor1;
  }else if (type == ButtonItemType_White){
    attrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
  }else {
    attrs[NSForegroundColorAttributeName] = GOrangeColor;
  }
  attrs[NSFontAttributeName] = [UIFont systemFontOfSize:GNormalFontSize];
  [buttonItem setTitleTextAttributes:attrs forState:UIControlStateNormal];
}


//导航栏使用图片创建左右按钮
- (UIButton *)navigationItemWithImage:(NSString *)imageName {
  UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
  UIImage *image = [UIImage imageNamed:imageName];
  CGFloat width = 30;
  CGFloat height = 30;
  //    CGFloat width = image.size.width < 40?40:image.size.width;
  //    CGFloat height = image.size.height < 40?40:image.size.height;
  [btn setImage:image forState:UIControlStateNormal];
  btn.frame = CGRectMake(0, 0, width, height);
  return btn;
}


//获取当前顶层的navController
- (UINavigationController *)getCurrNavController{
  UITabBarController *tabBarControler = (id)UIApplication.sharedApplication.delegate.window.rootViewController;
  UINavigationController *navController = tabBarControler.selectedViewController;
  return navController;
}

//获取当前顶层的viewController
- (UIViewController *)getCurrViewController{
  return [[self getCurrNavController].viewControllers lastObject];
}

// NSUserDefaults操作
- (void)setUserDefaultsWithKey:(NSString *)key andValue:(id)value {
  [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
}

- (NSString *)getUserDefaultsWithKey:(NSString *)key {
  NSString *value =
  (NSString *)[[NSUserDefaults standardUserDefaults] objectForKey:key];
  return value;
}

- (void)delUserDefaultsWithKey:(NSString *)key {
  [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}

//UITableView隐藏多余的分割线
- (void)setExtraCellLineHidden:(UITableView *)tableView {
  UIView *view = [[UIView alloc] init];
  view.backgroundColor = [UIColor clearColor];
  [tableView setTableFooterView:view];
}

//补全分割线
- (void)fullSperatorLine:(UITableView *)tableView {
  if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
  }
  
  if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
    [tableView setLayoutMargins:UIEdgeInsetsZero];
  }
}

//压缩图片
- (UIImage *)compressImage:(UIImage *)image {
  CGSize size = image.size;
  
  // 对图片大小进行压缩
  if (size.width >= 1024 || size.height >= 1024) {
    float a = size.width > size.height ? size.height : size.width;
    float b = 320;
    float scaled = b/a;
    
    size.height *= scaled;
    size.width *= scaled;
    
    UIImage * imageNew = [self imageWithImage:image scaledToSize:size];
    float compressSize = 0.6;
    NSData *imageData = UIImageJPEGRepresentation(imageNew,compressSize);
    imageNew = [UIImage imageWithData:imageData];
    
    if (DEBUG) {
      NSLog(@"Image file size: %.2fK", [self getImageFileSize:imageNew]/1024);
      NSLog(@"Image file size old: %.2fK", [self getImageFileSize:image]/1024);
    }
    return imageNew;
  } else {
    if (DEBUG) {
      NSLog(@"Image file size: %.2fK", [self getImageFileSize:image]/1024);
      NSLog(@"Image file size old: %.2fK", [self getImageFileSize:image]/1024);
    }
    return image;
  }
}

// 对图片尺寸进行压缩
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
  // Create a graphics image context
  UIGraphicsBeginImageContext(newSize);
  [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
  UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return newImage;
}

// 获取图片大小
- (float)getImageFileSize:(UIImage *)image {
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSString *imageName = @"tmpImg";
  
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *path = [paths objectAtIndex:0];
  NSString *filePath = [path stringByAppendingPathComponent:imageName];
  
  NSData *imageData = UIImageJPEGRepresentation(image,1);
  
  BOOL ret = [fileManager createFileAtPath:filePath contents:imageData attributes:nil];
  if (ret) {
    return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
  }
  return 0;
}

//图片缩放
- (UIImage *)fitSmallImage:(UIImage *)originImage
                  wantSize:(CGSize)wantSize
                  fitScale:(BOOL)flag {
  CGRect drawRect = CGRectZero;
  if (flag == YES) {
    //按宽高比例调整
    CGSize imageSize = originImage.size;
    CGFloat wscale = imageSize.width / wantSize.width;
    CGFloat hscale = imageSize.height / wantSize.height;
    CGFloat scale = (wscale > hscale) ? wscale : hscale;
    CGSize newSize =
    CGSizeMake(imageSize.width / scale, imageSize.height / scale);
    drawRect.size = newSize;
  } else {
    //不按宽高比调整
    drawRect.size = wantSize;
  }
  UIGraphicsBeginImageContext(drawRect.size);
  [originImage drawInRect:drawRect];
  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return newImage;
}

//图片沿另外图片剪裁
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
  CGImageRef maskRef = maskImage.CGImage;
  CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                      CGImageGetHeight(maskRef),
                                      CGImageGetBitsPerComponent(maskRef),
                                      CGImageGetBitsPerPixel(maskRef),
                                      CGImageGetBytesPerRow(maskRef),
                                      CGImageGetDataProvider(maskRef), NULL, false);
  CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
  return [UIImage imageWithCGImage:masked];
}

//获取文本高度
- (float) heightForString:(NSString *)value maxSize:(CGSize)maxSize attrs:(NSDictionary *)attrs{
  CGSize size = [value boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
  return size.height;
}

#pragma mark - autolayout
//设置Autolayout中的边距辅助方法
- (void)setEdge:(UIView *)superview
           view:(UIView *)view
           attr:(NSLayoutAttribute)attr
       constant:(CGFloat)constant {
  [superview
   addConstraint:[NSLayoutConstraint constraintWithItem:view
                                              attribute:attr
                                              relatedBy:NSLayoutRelationEqual
                                                 toItem:superview
                                              attribute:attr
                                             multiplier:1.0
                                               constant:constant]];
}

//设置view相对于superview的约束，-1表示不设置
- (void)setEdge:(UIView *)superview
           view:(UIView *)view
      edgeInset:(UIEdgeInsets)inset {
  if (inset.top != -1) {
    [self setEdge:superview
             view:view
             attr:NSLayoutAttributeTop
         constant:inset.top];
  }
  if (inset.left != -1) {
    [self setEdge:superview
             view:view
             attr:NSLayoutAttributeLeft
         constant:inset.left];
  }
  if (inset.right != -1) {
    [self setEdge:superview
             view:view
             attr:NSLayoutAttributeRight
         constant:-inset.right];
  }
  if (inset.bottom != -1) {
    [self setEdge:superview
             view:view
             attr:NSLayoutAttributeBottom
         constant:-inset.bottom];
  }
}
//添加左右间隔
- (void)addHorMargin:(UIView *)leftView
           rightView:(UIView *)view
               width:(CGFloat)width {
  [leftView.superview
   addConstraint:[NSLayoutConstraint
                  constraintWithItem:view
                  attribute:NSLayoutAttributeLeft
                  relatedBy:NSLayoutRelationEqual
                  toItem:leftView
                  attribute:NSLayoutAttributeRight
                  multiplier:1.0
                  constant:width]];
}
//添加上下间隔
- (void)addVerMargin:(UIView *)topView
          bottomView:(UIView *)view
               width:(CGFloat)width {
  [topView.superview
   addConstraint:[NSLayoutConstraint
                  constraintWithItem:view
                  attribute:NSLayoutAttributeTop
                  relatedBy:NSLayoutRelationEqual
                  toItem:topView
                  attribute:NSLayoutAttributeBottom
                  multiplier:1.0
                  constant:width]];
}

//定制宽高
//定制宽高
- (void)addConstraintWidth:(CGFloat)width
                    height:(CGFloat)height
                      view:(UIView *)view {
  if (width != -1) {
    [view addConstraint:[NSLayoutConstraint
                         constraintWithItem:view
                         attribute:NSLayoutAttributeWidth
                         relatedBy:NSLayoutRelationEqual
                         toItem:nil
                         attribute:NSLayoutAttributeNotAnAttribute
                         multiplier:1.0
                         constant:width]];
  }
  if (height != -1) {
    [view addConstraint:[NSLayoutConstraint
                         constraintWithItem:view
                         attribute:NSLayoutAttributeHeight
                         relatedBy:NSLayoutRelationEqual
                         toItem:nil
                         attribute:NSLayoutAttributeNotAnAttribute
                         multiplier:1.0
                         constant:height]];
  }
}

- (NSLayoutConstraint *)findFirstConstraint:(UIView *)parentView
                                  firstItem:(id)firstItem
                                  attribute:(NSLayoutAttribute)attribute {
  for (NSLayoutConstraint *constraint in parentView.constraints) {
    if ((constraint.firstItem == firstItem) &&
        (constraint.firstAttribute == attribute)) {
      return constraint;
    }
  }
  return nil;
}

- (NSLayoutConstraint *)findSecondConstraint:(UIView *)parentView
                                  secondItem:(id)secondItem
                                   attribute:(NSLayoutAttribute)attribute {
  for (NSLayoutConstraint *constraint in parentView.constraints) {
    
    if ((constraint.secondItem == secondItem) &&
        (constraint.secondAttribute == attribute)) {
      return constraint;
    }
  }
  return nil;
}

#pragma mark 删除所有tmp文件下的plist文件
- (void)deleteAllPlist:(void (^)(BOOL isSuccess))block {
  dispatch_async(
                 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                 , ^{
                   NSString *tmpDir = NSTemporaryDirectory();
                   NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:tmpDir];
                   for (NSString *p in files) {
                     NSError *error;
                     NSString *path = [tmpDir stringByAppendingPathComponent:p];
                     if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                       [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                     }
                   }
                   block(YES);
                 });
}

#pragma mark 获取本地版本号
- (NSString *)getLocalVersion{
  NSDictionary *infoDic = [NSBundle mainBundle].infoDictionary;
  NSString *localVersion = infoDic[@"CFBundleShortVersionString"];
  return localVersion;
}


#pragma mark 设置按钮样式（上图片下文字）
- (void)setBtnDownTextStyle:(UIButton *)btn {
  btn.titleEdgeInsets = UIEdgeInsetsMake(0.0, -btn.imageView.width, -btn.imageView.height, 0.0);
  btn.imageEdgeInsets = UIEdgeInsetsMake(-btn.titleLabel.intrinsicContentSize.height, 0.0, 0.0, -btn.titleLabel.intrinsicContentSize.width);
  CGFloat offset = 10;
  btn.titleEdgeInsets = UIEdgeInsetsMake(0.0,  -btn.imageView.width,  -btn.imageView.height - offset / 2, 0.0);
  btn.imageEdgeInsets = UIEdgeInsetsMake( -btn.titleLabel.intrinsicContentSize.height - offset / 2, 0.0, 0.0, -btn.titleLabel.intrinsicContentSize.width);
}

#pragma mark 设置导航栏风格
- (void)setNavAndStatusBar:(UINavigationBar *)navBar style:(NavStyle)style{
  
  if (style == NavStyle_Black) {
    //状态栏前景
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    //状态栏、导航栏背景
    navBar.barTintColor = GBlackColor;
    //导航栏title
    [navBar setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:GLargeFontSize], NSForegroundColorAttributeName : [UIColor whiteColor]}];
    //导航栏按钮
    navBar.tintColor = [UIColor whiteColor];

  }else{
    //状态栏前景
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    //状态栏、导航栏背景
    navBar.barTintColor = [UIColor whiteColor];
    //导航栏title
    [navBar setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:GLargeFontSize], NSForegroundColorAttributeName : GBlackColor}];
    //导航栏按钮
    navBar.tintColor = GGrayWordColor2;
  }
}


#pragma mark json转字典
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
  if (jsonString == nil) {
    return nil;
  }
  
  NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  NSError *err;
  NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                      options:NSJSONReadingMutableContainers
                                                        error:&err];
  if (err) {
    NSLog(@"json解析失败：%@", err);
    return nil;
  }
  return dic;
}

@end
